package job;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import models.Channelpermissions;
import models.Order;
import models.Organization;
import param.pub.Publicrequest;
import param.unlock.Unlockrequest;
import param.unlock.Unlockresponse;
import play.Logger;
import play.db.jpa.JPA;
import play.jobs.Job;
import service.ws.NetTicketSellServiceImplSoapProxy;
import utils.LogUtil;
import utils.PublicInfoUtil;
import utils.PublicXmlUtil;
import utils.XmlUtil;

@SuppressWarnings("rawtypes")
//@Every("5s")
public class AutoUnlockSeatJob extends Job {
	public void doJob() {
		List<Order> orders=Order.findBy_status("0");
		
		if(orders !=null && orders.size()>0){
			for(int i=0;i<orders.size();i++){
				Order order=orders.get(i);
				Date autounlocktime=getLockTime(order.lockdelay, order.locktime);
				Date date=new Date();
				if(date.compareTo(autounlocktime)>0){
					Unlockrequest unlockrequest=new Unlockrequest();
					Unlockresponse unlockres = null;
					Publicrequest publicrequest=PublicXmlUtil.newHLJPublicrequest();
					Organization organization = null;
					String sql = "select o from Organization o where o.isactive=1 and o.code='" + order.departorgcode + "'";
					Query queryOrganization = JPA.em().createQuery(sql);
					try {
						organization = (Organization) queryOrganization.getSingleResult();
					} catch (Exception e) {
						LogUtil.logerror("未找到机构信息");
						return;
					}
					publicrequest.setTargetorgcode(organization.code);
					
					unlockrequest.setPublicrequest(publicrequest);
					unlockrequest.setOrderno(order.orderno);
					unlockrequest.setNetticketid("");
					
					String xmlString=PublicInfoUtil.toXml(unlockrequest);
					String netTicketSellServiceImplPort_address = "http://" + organization.serversaddress + "/WebServiceDBServer/NetSaleServiceImplService.asmx";
					NetTicketSellServiceImplSoapProxy proxy = new NetTicketSellServiceImplSoapProxy(netTicketSellServiceImplPort_address);
					try {
						String resultXml = proxy.unlock(xmlString);
						unlockres = (Unlockresponse) XmlUtil.toBean(resultXml, Unlockresponse.class);
						if(unlockres!=null&&unlockres.getPublicresponse()!=null&&"0000".equals(unlockres.getPublicresponse().getResultcode())){
							//车站解锁成功，更新中心的订单状态
							Order resultorder = Order.findBy_orderno(unlockrequest.getOrderno());
							if (order != null) {
								//恢复额度
								Channelpermissions channelpermissions = Channelpermissions.findBy_orgcode(resultorder.sellorgcode, false);
								double countprice = resultorder.amount;
								if(countprice != 0.0 && channelpermissions != null){
									channelpermissions.usefulquota = channelpermissions.usefulquota + countprice;
									Channelpermissions departChannelpermissions = Channelpermissions.findBy_orgcode(order.departorgcode, false);
									if (!JPA.em().getTransaction().isActive()) {
										JPA.em().getTransaction().begin();
									}
									if(departChannelpermissions != null ){
										departChannelpermissions.bysellamount = departChannelpermissions.bysellamount - countprice;
										departChannelpermissions.save();
									}
									channelpermissions.save();
								}
								resultorder.status = ("2");
								resultorder.updatetime = (new Date());
								JPA.em().persist(resultorder);
//								JPA.em().getTransaction().commit();	
							}
						}
					} catch (Exception e) {
						Logger.log4j.error("自动解锁失败", e);
					}
					
				}
			}
		}
	}
	
	/**
	 * 根据期望锁定时间、取出可锁定时长(秒)
	 * 
	 * @param locktime
	 *            锁定时间
	 * @param hopeLockMinute
	 *            期望锁定分钟数
	 * @return
	 * @throws Exception
	 */
	private Date getLockTime(float hopeLockMinute,  Date locktime) {
		Calendar cld = Calendar.getInstance();
		cld.setTime(locktime);
		int locktimeout = 0;
		if (hopeLockMinute > 0) {
			// 通过售票方式，验证期望锁定时间是否超过限制
			locktimeout = (int) (hopeLockMinute * 60); // 订单购票锁位时长，单位为秒钟
		} else {
			locktimeout = (int) (40 * 60); // 订单购票锁位时长，单位为秒钟
		}
		cld.add(Calendar.SECOND, locktimeout);
		return cld.getTime();
	}
}
